<?php
namespace App\Http\Logic;

use App\Enums\UserEnum;
use App\Models\SwtUser;
use App\Services\AdminService;
use App\Services\AliPayService;
use App\Services\WechatService;
use Illuminate\Support\Facades\Cache;

class UserLogic extends BaseLogic
{
    /**
     * @notes 微信支付宝登录用户
     * @param $open_id
     * @param $source_type
     * @return mixed
     * @author Evil丿
     * @date 2024/08/23 16:32
     */
    public static function loginByOpenId($code, $source_type)
    {
        $where = [];

        switch($source_type)
        {
            case 0:
                $service = new WechatService();
                $wechat_info = $service -> getOpenId($code);
                $open_id = $wechat_info['openid'];
                $where['wechat_open_id'] = $open_id;
                $name = 'mini-wechat';
            break;
            case 1:
                $service = new AliPayService();
                $open_id = $service -> getOpenId($code);
                $where['alipay_open_id'] = $open_id;
                $name = 'mini-alipay';
            break;
        }
        $user_info = SwtUser::where($where) -> first();

        if(!$user_info || empty($user_info -> mobile)) {
            $cache = MD5($open_id);

            Cache::put('open_id_' . $cache, json_encode($where), 60 * 60);

            return [
                'code'    => 256,
                'message' => '未绑定手机号',
                'data'    => [
                    'cache' => $cache
                ]
            ];
        }

        if($user_info -> status == UserEnum::USER_DISABLED) {
            self::$error = "用户已被冻结";
            return false;
        }

        return  [
            'code'    => 200,
            'message' => '登录成功',
            'data'    => [
                'token' => AccessTokenLogic::getAccessToken($user_info, $name)
            ]
        ];
    }

    /**
     * @notes 微信支付宝注册用户
     * @param $code
     * @param $cache
     * @param $source_type
     * @return bool
     * @throws \Illuminate\Http\Client\RequestException
     * @author Evil丿
     * @date 2024/08/23 17:21
     */
    public static function registerByMobile($code, $cache, $source_type)
    {
        $cache_info = Cache::get('open_id_'. $cache);

        if(!$cache_info) {
            self::$error = '用户授权信息失效或不存在';
            return false;
        }

        $data = json_decode($cache_info, true);

        switch($source_type)
        {
            case 0:
                $service = new WechatService();

                $phone_info = $service -> getPhoneNumber($code);

                $data['mobile'] = $phone_info['purePhoneNumber'];
                break;
            case 1:
                $service = new AliPayService();

                $phone = $service -> getPhoneNumber($code);

                $data['mobile'] = $phone;
                break;
        }

        if(!$data['mobile']) {
            self::$error = '手机号获取失败';
            return false;
        }
        $res = self::saveUserInfo($data);

        if(!$res) {
            self::$error = '用户注册失败';
            return false;
        }

        Cache::forget('open_id_'. $cache);

        return true;
    }

    /**
     * @notes 新增用户
     * @param $data
     * @return mixed
     * @author Evil丿
     * @date 2024/04/03 15:49
     */
    public static function saveUserInfo($data)
    {
        $user = SwtUser::firstWhere('mobile', $data['mobile']);

        if($user) {
            $data['name'] = $user -> name ? : create_user_sn('U');

            $data['avatar'] = $user -> avatar ? : 'images/avatar/default_'.rand(1,12).'.png';
        } else {
            $data['name'] = create_user_sn('U');

            $data['avatar'] = 'images/avatar/default_'.rand(1,12).'.png';
        }

        $res = SwtUser::updateOrCreate(['mobile'=>$data['mobile']], $data);

        return $res;
    }

    /**
     * @notes 根据ID获取用户信息
     * @param $user_id
     * @return mixed
     * @author Evil丿
     * @date 2024/04/03 15:48
     */
    public static function getUserInfo($where) {
        return SwtUser::where($where) -> first();
    }

    /**
     * @notes 编辑用户信息
     * @param $id
     * @param $data
     * @return mixed
     * @author Evil丿
     * @date 2024/04/03 15:49
     */
    public static function editUserInfo($id, $data)
    {
        $res = SwtUser::where('id', $id) -> update($data);

        return $res;
    }

    public static function getLoginToken($id, $type)
    {
        $user_info = SwtUser::firstWhere('id', $id);

        return  [
            'code'    => 200,
            'message' => '登录成功',
            'data'    => [
                'token' => AccessTokenLogic::getAccessToken($user_info, $type)
            ]
        ];
    }

    public static function getCardUserInfo($user_id)
    {
        $user_info = SwtUser::firstWhere('id', $user_id);

        if(!$user_info -> mobile) {
            self::$error = "用户非会员卡用户";
            return false;
        }

        $info = AdminService::getCardUserInfo(['mobile' => $user_info -> mobile]);

        if(empty($info)) {
            self::$error = "用户非会员卡用户";
            return false;
        }

//        if($info['balance'] < 20) {
//            self::$error = "会员卡余额不足";
//            return false;
//        }

        if($user_info['card_id'] !== $info['member_id']) {
            $user_info -> card_id = $info['member_id'];
            $user_info -> save();
        }

        return true;
    }
}
